import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { getLoginUserUsingGet } from "@/api/userController";
import ACCESS_ENUM from "@/assess/accessEnum";

/**
 * LoginUserInfo Global state
 */
export const useLoginUserStore = defineStore("loginUser", () => {
  /**
   * LoginUserInfo state
   */
  const loginUser = ref<API.LoginUserVO>({
    userName: "未登录",
  });

  /**
   * Set LoginUserInfo
   * @param newLoginUser
   */
  function setLoginUser(newLoginUser: API.LoginUserVO) {
    loginUser.value = newLoginUser;
  }

  /**
   * Remote Get LoginUserInfo
   */
  async function fetchLoginUser() {
    const res = await getLoginUserUsingGet(); //Asynchronous to synchronous
    // 登录成功
    if (res.data.code === 0 && res.data.data) {
      loginUser.value = res.data.data;
    } else {
      // 登录失败(模拟数据)
      // setTimeout(() => {
      //   loginUser.value = {
      //     id: 1,
      //     userName: "已登陆",
      //     userRole: ACCESS_ENUM.ADMIN,
      //   };
      // }, 30000);
      loginUser.value = { userRole: ACCESS_ENUM.NOT_LOGIN };
    }
  }
  //Computed properties
  return { loginUser, setLoginUser, fetchLoginUser };
});
